//数据操作
const fs = require('fs')
const path = require('path')
const static = require('koa-static')
const query = require('../db/query')
const dbPath = path.join('C:/Users/DELL/Desktop/10.1zuoye/demo/app/db','userDb.json')
//新增
const addUserService = async (params) => {
    let myData = await JSON.parse(fs.readFileSync(dbPath, 'utf-8'))
    myData.push(params)
    await fs.writeFileSync(dbPath, JSON.stringify(myData), 'utf-8')
    return true
}
//删除
const deleteUserService = async (params) => {
    let myData = await JSON.parse(fs.readFileSync(dbPath, 'utf-8'))
    let arr = []
    await myData.forEach(item => {
        if(item.id == params){
            arr.push(item)
        }
    })
    await fs.writeFileSync(dbPath, JSON.stringify(arr), 'utf-8')
    return true
}
//修改
const putUserService = async (params) => {
    let myData = await JSON.parse(fs.readFileSync(dbPath, 'utf-8'))
    let fileters = await myData.splice(v=>{
        return v.id = params;
    })
    // let arr = []
    if(fileters[0]){
        fileters[0].username = params.username
        fileters[0].password = params.password
        fileters[0].nickname = params.nicekname
        fileters[0].age = params.age
        fileters[0].phone = params.phone
    }
    await fs.writeFileSync(dbPath, JSON.stringify(fileters), 'utf-8')
    return true
}
//查询
const getUserService = async (params) => {
    let myData = await JSON.parse(fs.readFileSync(dbPath, 'utf-8'))
    let arr = []
    if(params){
        myData.forEach(item => {
            if(item.id == params){
                arr.push(item)
            }
        })
        await fs.writeFileSync(dbPath, JSON.stringify(arr), 'utf-8')
        return true
    }
}

module.exports = {
    addUserService,
    deleteUserService,
    putUserService,
    getUserService,
}